package com.gp.pj.utils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 45709
 */
public class MD5Utils {

    public static final String SALT = "1013TUtianrui**";

    public static String encodePwd(String passWord) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //加密
        String hexPwd = MD5(passWord);
        //加盐操作
        StringBuilder builder = new StringBuilder(hexPwd);

        String salt = MD5(SALT);
        builder.insert(18, salt);
        //返回加密加盐后的字符串
        return builder.toString();
    }

    public static String MD5(String passWard){
        try {
            //MessageDigest是封装md5算法的工具对象还支持SHA算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            //通过digest拿到的任意字符串,得到的bates都是等长的
            byte[] bytes = md.digest(passWard.getBytes(StandardCharsets.UTF_8));
            passWard = toHex(bytes);
            return passWard;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串转换成16进制
     */
    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        //循环判断是为了补位操作
        for (byte aByte : bytes) {
            ret.append(HEX_DIGITS[(aByte >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[aByte & 0x0f]);
        }
        return ret.toString();
    }

}
